package com.drotposta.unitils;

import com.drotposta.unitils.impl.PrincipalImpl;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;

/**
 *
 * @author elek
 */
public class Directory {

    private Map<String, EntityManager> em = new HashMap<String, EntityManager>();

    private java.security.Principal principal = new PrincipalImpl("ANONYMOUS");

    private String defaultPersistenceUnit;

    public static final String ANNONYMOUS_USER = "annonymous";

    public static final String ENTITY_MANAGER = "EntityManager";

    public Map<String, Object> contents = new HashMap();

    public Object getEjb(Class clazz) {
        return contents.get("ejb/" + clazz.getCanonicalName());
    }

    public EntityManager getEntityManager() {
        return getEntityManager(defaultPersistenceUnit);
    }

    public EntityManager getEntityManager(String persistenceUnit) {
        if (persistenceUnit == null || persistenceUnit.length() == 0) {
            persistenceUnit = defaultPersistenceUnit;
        }
        if (em.get(persistenceUnit) == null) {
            System.out.println("CREATE entity manager: " + persistenceUnit);
            em.put(persistenceUnit, Persistence.createEntityManagerFactory(persistenceUnit).createEntityManager());
//            contents.put(ENTITY_MANAGER, em);
        }
        return em.get(persistenceUnit);
    }

    public EntityTransaction getEntityTransaction() {
        return getEntityManager().getTransaction();
    }

    public java.security.Principal getPrincipal() {
        return principal;
    }

    public void setPrincipalName(String name) {
        ((PrincipalImpl) this.principal).setName(name);
    }

    void resetEm() {
        for (Iterator<String> it = em.keySet().iterator(); it.hasNext();) {
            em.get(it.next()).close();
            it.remove();
        }
    }

    void setPersistenceUnit(String persistenceUnit) {
        this.defaultPersistenceUnit = persistenceUnit;
    }
}
